local sk__chezheng = fk.CreateSkill {

  name = "sk__chezheng",

  tags = {  },

}



sk__chezheng:addEffect(fk.EventPhaseEnd, {
  name = "sk__chezheng",
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(sk__chezheng.name) and player.phase == Player.Play and
      player:usedSkillTimes(sk__chezheng.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local _, dat = player.room:askForUseActiveSkill(player, "sk__chezheng_active",
      "#sk__chezheng-invoke:::"..player.hp, true, nil, false)
    if dat then
      event:setCostData(self, dat)
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:sortByAction(table.map(event:getCostData(self).targets,Util.Id2PlayerMapper))
    local tos = {}
    local targets = table.map(event:getCostData(self).targets, Util.Id2PlayerMapper)
    for _, p in ipairs(targets) do
      if not p.dead then
        if event:getCostData(self).interaction == "sk__chezheng_discard" then
          room:askForDiscard(p, 1, 1, true, sk__chezheng.name, false, ".", "#sk__chezheng-discard")
        else
          p:drawCards(1, sk__chezheng.name)
        end
      end
      if not p.dead then
        table.insert(tos, p)
      end
    end
    tos = table.reverse(tos)
    for _, p in ipairs(tos) do
      if event:getCostData(self).interaction == "sk__chezheng_discard" then
        p:gainAnExtraPhase(Player.Play)
      else
        p:gainAnExtraPhase(Player.Discard)
      end
    end
  end,
})

return sk__chezheng